﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CustomControls;
using DataAccess;
using Model.EntityModel;
using CheckBox = System.Windows.Controls.CheckBox;
using GroupBox = System.Windows.Controls.GroupBox;
using PrintDialog = System.Windows.Controls.PrintDialog;
using TextBox = System.Windows.Controls.TextBox;
using UserControl = System.Windows.Controls.UserControl;

namespace Project
{
    /// <summary>
    /// Interaction logic for RegisterComplaintContent.xaml
    /// </summary>
    public partial class RegisterComplaintContent : UserControl
    {
        public Complaint CurrentComplaint { get; set; }
        public RegisterComplaintPart2 regPart2 { get; set; }

        public RegisterComplaintContent(Nullable<long> complaintId)
        {
            InitializeComponent();
            cboxCompCountry.ItemsSource = GetCountryList();
            cboxCompCountry.SelectedValue = "Bolivia";
            cbVictimCountry.ItemsSource = GetCountryList();
            cbVictimCountry.SelectedValue = "Bolivia";
            cbAggressorCountry.ItemsSource = GetCountryList();
            cbAggressorCountry.SelectedValue = "Bolivia";
            lblCaseNumber.Content = ComplaintDataAccess.GetLastComplaintId()+1;
            lblRegistrationDate.Content = DateTime.Now.ToShortDateString();
            SetFieldRestrictions();
            if (complaintId == null)
                complaintId = 0;
            CurrentComplaint = ComplaintDataAccess.GetComplaintById((long)complaintId);
            if (CurrentComplaint != null)
                SetFieldInfoAndLocks();
        }


        private void SetFieldInfoAndLocks()
        {
            lblCaseNumber.Content = CurrentComplaint.Id;
            Person complainant = new Person();
            Person aggressor = new Person();
            UIWindowManager.SetWindowTitle(this,"Brigada De Protección a la Familia - Completar registro denuncia");
            Loaded += SetCustomTitle;
            foreach (var actor in CurrentComplaint.Actor)
            {
                if(actor.Type=="Denunciante")
                    complainant = actor.Person;
                if(actor.Type=="Agresor")
                    aggressor = actor.Person;
            }
            //Complainant Info
            tbCompName.Text = complainant.Name;
            tbCompName.IsReadOnly = true;
            tbCompLastName.Text = complainant.PaternalName;
            tbCompLastName.IsReadOnly = true;
            tbCompMiddleName.Text = complainant.MaternalName;
            tbCompMiddleName.IsReadOnly = true;
            tbCompCI.Text = complainant.CiPassport.ToString();
            tbCompCI.IsReadOnly = true;
            tbCompPhone.Text = complainant.Phone;
            tbCompPhone.IsReadOnly = true;
            CompBornDate.SelectedDate = complainant.BirthDate;
            CompBornDate.IsHitTestVisible = false;
            tbCompJob.Text = complainant.Ocupation;
            tbCompJob.IsReadOnly = true;
            cbCompCivilStatus.SelectedValue = complainant.CivilStatus;
            cbCompCivilStatus.IsHitTestVisible = false;
            tbCompAddress.Text = complainant.Address;
            tbCompAddress.IsReadOnly = true;
            tbCompZone.Text = complainant.Zone;
            tbCompZone.IsReadOnly = true;

            //Aggressor Info
            tbAggressorName.Text = aggressor.Name;
            tbAggressorName.IsReadOnly = true;
            tbAggressorLastName.Text = aggressor.PaternalName;
            tbAggressorLastName.IsReadOnly = true;
            tbAggressorMiddleName.Text = aggressor.MaternalName;
            tbAggressorMiddleName.IsReadOnly = true;
            tbAggressorCi.Text = aggressor.CiPassport.ToString();
            tbAggressorCi.IsReadOnly = true;
            tbAggressorPhone.Text = aggressor.Phone;
            tbAggressorPhone.IsReadOnly = true;
            AggressorBornDate.SelectedDate = aggressor.BirthDate;
            AggressorBornDate.IsHitTestVisible = false;
            tbAggressorBornPlace.Text = aggressor.BornCity;
            tbAggressorBornPlace.IsReadOnly = true;
            cbAggressorCivilStatus.SelectedValue = aggressor.CivilStatus;
            cbAggressorCivilStatus.IsHitTestVisible = false;

            //Incident Info
            dateIncident.SelectedDate = CurrentComplaint.IncidentDate;
            dateIncident.IsHitTestVisible = false;

        }

        private void SetCustomTitle(object sender, RoutedEventArgs e)
        {
            Window w = Window.GetWindow(this.Parent);
            ((RegisterComplaint)((MainWindow)w).Content.Children[0]).UseCaseTitle.Text = "Completar Registro de Denuncia";
        }


        private void SetFieldRestrictions()
        {
            //Date Restrictions
            CompBornDate.DisplayDateEnd = DateTime.Now;
            CompBornDate.DisplayDateStart = DateTime.Now.AddYears(-100);
            AggressorBornDate.DisplayDateEnd = DateTime.Now;
            AggressorBornDate.DisplayDateStart = DateTime.Now.AddYears(-100);
            VictimBornDate.DisplayDateEnd = DateTime.Now;
            VictimBornDate.DisplayDateStart = DateTime.Now.AddYears(-100);
            dateIncident.DisplayDateEnd = DateTime.Now;
            dateIncident.DisplayDateStart = DateTime.Now.AddMonths(-1);
            //TexBox Restrictions
            tbCompPhone.DeactivateBlankValidation();
            tbCompPhone.AddValitationRule(new PhoneValidationRule());
            tbVictimPhone.DeactivateBlankValidation();
            tbVictimPhone.AddValitationRule(new PhoneValidationRule());
            tbAggressorPhone.DeactivateBlankValidation();
            tbAggressorPhone.AddValitationRule(new PhoneValidationRule());
            tbCompZone.DeactivateBlankValidation();
            tbCompName.AddValitationRule(new LenghtValidationRule(3));
            tbCompLastName.AddValitationRule(new LenghtValidationRule(3));
            tbCompMiddleName.AddValitationRule(new LenghtValidationRule(3));
            tbCompCI.AddValitationRule(new LenghtValidationRule(6));
            tbCompAddress.AddValitationRule(new LenghtValidationRule(8));
            tbAggressorName.AddValitationRule(new LenghtValidationRule(3));
            tbAggressorLastName.AddValitationRule(new LenghtValidationRule(3));
            tbAggressorMiddleName.AddValitationRule(new LenghtValidationRule(3));
            tbAggressorCi.AddValitationRule(new LenghtValidationRule(6));
            tbAggressorBornPlace.AddValitationRule(new LenghtValidationRule(4));
            tbVictimName.AddValitationRule(new LenghtValidationRule(3));
            tbVictimLastName.AddValitationRule(new LenghtValidationRule(3));
            tbVictimMiddleName.AddValitationRule(new LenghtValidationRule(3));
            tbVictimCI.AddValitationRule(new LenghtValidationRule(6));
            tbVictimBornPlace.AddValitationRule(new LenghtValidationRule(4));
            tbDescription.DeactivateBlankValidation();
        }

        private List<string> GetCountryList()
        {
            List<string> cultureList = new List<string>();
            CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
            foreach (CultureInfo culture in cultures)
            {
                if (!culture.IsNeutralCulture && culture.LCID != 0x7F)
                {
                    RegionInfo region = new RegionInfo(culture.LCID);
                    if (!(cultureList.Contains(region.DisplayName)))
                        cultureList.Add(region.DisplayName);
                }
            }
            var sortedList = (from culture in cultureList
                              orderby culture
                              select culture).ToList();
            return sortedList;
        }


        public void SaveFirstPartOfComplaint(string IncidentDetail)
        {
            Complaint newComplaint = null;
            newComplaint = GatherComlpaintInfo();
            newComplaint.IncidentDetail = IncidentDetail;
            if (CurrentComplaint == null)
                newComplaint = ComplaintDataAccess.RegisterComplaint(newComplaint);
            else
            {
                newComplaint = ComplaintDataAccess.UpdateComplaint(CurrentComplaint.Id, newComplaint);
            }
            GetComplainantActorInfo(newComplaint.Id);
            GetAggressorActorInfo(newComplaint.Id);
            PhotoAlbumDataAccess.InsertImageToComplaint(newComplaint.Id, tbAggressorImage.Text, "Agresor.jpg");
            GetVictimActorInfo(newComplaint.Id);
            PhotoAlbumDataAccess.InsertImageToComplaint(newComplaint.Id, tbVictimImage.Text, "Victima.jpg");
            var violenceCauses = GatherViolenceCauses(newComplaint.Id);
            foreach (var violenceCause in violenceCauses)
            {
                ComplaintDataAccess.InsertViolenceCause(violenceCause);
            }
            var violenceForms = GatherViolenceForms(newComplaint.Id);
            foreach (var violenceForm in violenceForms)
            {
                ComplaintDataAccess.InsertViolenceForm(violenceForm);
            }
            var multidisTeam = GatherMultidisciplinaryTeam(newComplaint.Id);
            foreach (var multidisciplinaryTeam in multidisTeam)
            {
                ComplaintDataAccess.InsertMultidisciplinaryTeam(multidisciplinaryTeam);
            }
            var caseDerivations = GatherCaseDerivations(newComplaint.Id);
            foreach (var caseDerivation in caseDerivations)
            {
                ComplaintDataAccess.InsertCaseDerivation(caseDerivation);
            }
        }

        private void SaveAndContinue_Click(object sender, RoutedEventArgs e)
        {
            bool hasErrors = CheckHasErrors();
            if (!hasErrors)
            {
                if(regPart2==null)
                    regPart2 = new RegisterComplaintPart2(this);
                var par = this.Parent as ItemsControl;
                par.Items.Clear();
                var scrollView = (par.Parent as ItemsControl).Parent as ScrollViewer;
                scrollView.ScrollToTop();
                par.Items.Add(regPart2);
            }
            else
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Se deben llenar todos los campos indicados para poder continuar!", "Error!",MessageBoxButton.OK,MessageBoxImage.Error);
            }
        }

        private bool CheckHasErrors()
        {
            bool res = false;
            foreach (var control in Content.Children)
            {
                GroupBox gp = control as GroupBox;
                if (gp != null)
                {
                    foreach (var ctrl in (gp.Content as Grid).Children)
                    {
                        MaskTextBox tb = ctrl as MaskTextBox;
                        if (tb != null)
                        {
                            tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();
                            if (Validation.GetHasError(tb))
                                res = true;
                        }
                        ValidationComboBox cb = ctrl as ValidationComboBox;
                        if (cb != null)
                        {
                            cb.LostFocusEventHandler(cb,null);
                            if (Validation.GetHasError(cb))
                                res = true;
                        }
                        ValidDatePicker dtp = ctrl as ValidDatePicker;
                        if (dtp != null)
                        {
                            dtp.GetBindingExpression(DatePicker.TextProperty).UpdateSource();
                            dtp.LostFocusEventHandler(dtp, null);
                            if (Validation.GetHasError(dtp))
                                res = true;
                        }
                    }
                }
            }
            bool someCheck = false;
            foreach (var ctrl in ViolenceCause.Children)
            {
                CheckBox chckBox = ctrl as CheckBox;
                
                if (chckBox != null)
                    if (chckBox.IsChecked == true)
                        someCheck = true;
            }
            if (!someCheck)
            {
                lblViolenceCauseError.Content = "Debe seleccionar al menos una causa.";
                res = true;
            }
            if (!(rbtnPrivateAmbit.IsChecked == true || rbtnPublicAmbit.IsChecked == true))
            {
                lblIncidentPlaceError.Content = "Debe seleccionar alguno ambito.";
                res = true;
            }
            if (!(rbtnZoneCentral.IsChecked == true || rbtnZonePeriferic.IsChecked == true || rbtnZoneRural.IsChecked == true))
            {
                lblIncidentZoneError.Content = "Debe seleccionar alguna zona del hecho.";
                res = true;
            }
            someCheck = false;
            foreach (var ctrl in ViolenceForm.Children)
            {
                if (ctrl is CheckBox)
                    if ((ctrl as CheckBox).IsChecked == true)
                        someCheck = true;
            }
            if (!someCheck)
            {
                lblViolenceFormError.Content = "Debe seleccionar al menos una forma de violencia.";
                res = true;
            }
            if (!(chkArrest.IsChecked == true || chkMeeting.IsChecked == true))
            {
                lblCasesAtentionError.Content = "Debe seleccionar al menos una forma de atencion del caso.";
                res = true;
            }
            return res;
        }

        public Complaint GatherComlpaintInfo()
        {
            Complaint complaint = new Complaint();
            complaint.IncidentDate = dateIncident.SelectedDate;
            complaint.IncidentNature =
                ((PersonAndActorDataAccess.IsRelapse(long.Parse(tbVictimCI.Text), tbVictimName.Text,
                                                     tbVictimLastName.Text, tbVictimMiddleName.Text,
                                                     long.Parse(tbAggressorCi.Text), tbAggressorName.Text,
                                                     tbAggressorLastName.Text, tbAggressorMiddleName.Text))
                     ? "Reincidencia"
                     : "Denuncia Nueva");
            complaint.IncidentPlace = rbtnPrivateAmbit.IsChecked == true
                                          ? "Ambito Privado"
                                          : rbtnPublicAmbit.IsChecked == true ? "Ambito Publico" : null;
            complaint.IncidentZone = rbtnZoneCentral.IsChecked == true
                                         ? "Urbano Central"
                                         : (rbtnZoneRural.IsChecked == true
                                                ? "Rural"
                                                : rbtnZonePeriferic.IsChecked == true ? "Urbano Periferica" : null);
            complaint.CasesAttention = chkMeeting.IsChecked == true
                                           ? (chkArrest.IsChecked == true ? "Citacion Y Arresto" : "Citacion")
                                           : (chkArrest.IsChecked == true ? "Arresto" : null);
            complaint.ConductOfAgressor = rbtnAggressorTempSane.IsChecked == true
                                              ? "Sano"
                                              : (rbtnAggressorTempDrunk.IsChecked == true
                                                     ? "Ebriedad"
                                                     : rbtnAggressorTempDrugs.IsChecked == true ? "Drogas" : null);
            complaint.VictimAgressorRelationship =
                (cboxVictimPartnership.SelectedItem as ComboBoxItem).Content.ToString();
            complaint.ComplainantVictimRelationship =
                (cboxCompPartnership.SelectedItem as ComboBoxItem).Content.ToString();
                complaint.RegistrationDate = DateTime.Now;
                complaint.Status = false;
            return complaint;
        }

        public List<ViolenceCause> GatherViolenceCauses(long idComplaint)
        {
            List<ViolenceCause> violenceCauses = new List<ViolenceCause>();

            if (chkEconomics.IsChecked==true)
                violenceCauses.Add(new ViolenceCause { IdComplaint = idComplaint, Cause = chkEconomics.Content.ToString(), Status = false });
            if (chkFamiliar.IsChecked == true)
                violenceCauses.Add(new ViolenceCause { IdComplaint = idComplaint, Cause = chkFamiliar.Content.ToString(), Status = false });
            if (chkJealous.IsChecked == true)
                violenceCauses.Add(new ViolenceCause { IdComplaint = idComplaint, Cause = chkJealous.Content.ToString(), Status = false });
            if (chkInfidelity.IsChecked == true)
                violenceCauses.Add(new ViolenceCause { IdComplaint = idComplaint, Cause = chkInfidelity.Content.ToString(), Status = false });
            if (chkOthersNature.IsChecked == true)
                violenceCauses.Add(new ViolenceCause { IdComplaint = idComplaint, Cause = chkOthersNature.Content.ToString(), Status = false });
            if (chkDomainHabits.IsChecked == true)
                violenceCauses.Add(new ViolenceCause { IdComplaint = idComplaint, Cause = chkDomainHabits.Content.ToString(), Status = false });
           return violenceCauses;
        }

        public List<ViolenceForm> GatherViolenceForms(long idComplaint)
        {
            List<ViolenceForm> violenceForms = new List<ViolenceForm>();

            if(chkPhysics.IsChecked==true)
                violenceForms.Add(new ViolenceForm{ IdComplaint = idComplaint, Form = chkPhysics.Content.ToString(), Description = tbDescription.Text,Status = false});
            if (chkPsicologics.IsChecked == true)
                violenceForms.Add(new ViolenceForm { IdComplaint = idComplaint, Form = chkPsicologics.Content.ToString(), Description = tbDescription.Text, Status = false });
            if (chkSexual.IsChecked == true)
                violenceForms.Add(new ViolenceForm { IdComplaint = idComplaint, Form = chkSexual.Content.ToString(), Description = tbDescription.Text, Status = false });
            if (chkOthersViolenceForm.IsChecked == true)
                violenceForms.Add(new ViolenceForm { IdComplaint = idComplaint, Form = chkOthersViolenceForm.Content.ToString(), Description = tbDescription.Text, Status = false });

            return violenceForms;
        }

        public List<MultidisciplinaryTeam> GatherMultidisciplinaryTeam(long idComplaint)
        {
            List<MultidisciplinaryTeam> multidisciplinaryTeam = new List<MultidisciplinaryTeam>();
            if(chkMedic.IsChecked==true)
                multidisciplinaryTeam.Add(new MultidisciplinaryTeam{IdComplaint = idComplaint, Professional = chkMedic.Content.ToString(), Status = false});
            if (chkPsicology.IsChecked == true)
                multidisciplinaryTeam.Add(new MultidisciplinaryTeam { IdComplaint = idComplaint, Professional = chkPsicology.Content.ToString(), Status = false });
            if (chkSocialWorker.IsChecked == true)
                multidisciplinaryTeam.Add(new MultidisciplinaryTeam { IdComplaint = idComplaint, Professional = chkSocialWorker.Content.ToString(), Status = false });
            if (chkLegalAsessor.IsChecked == true)
                multidisciplinaryTeam.Add(new MultidisciplinaryTeam { IdComplaint = idComplaint, Professional = chkLegalAsessor.Content.ToString(), Status = false });
            return multidisciplinaryTeam;
        }

        public List<CaseDerivation> GatherCaseDerivations(long idComplaint)
        {
            List<CaseDerivation> caseDerivations = new List<CaseDerivation>();
            if (chkDerivJudge.IsChecked==true)
                caseDerivations.Add(new CaseDerivation { IdComplaint = idComplaint, Institution = chkDerivJudge.Content.ToString(), Status = false});
            if (chkDerivPublicMinistery.IsChecked == true)
                caseDerivations.Add(new CaseDerivation { IdComplaint = idComplaint, Institution = chkDerivPublicMinistery.Content.ToString(), Status = false });
            if (chkDerivFELCC.IsChecked == true)
                caseDerivations.Add(new CaseDerivation { IdComplaint = idComplaint, Institution = chkDerivFELCC.Content.ToString(), Status = false });
            if (chkDerivDefensory.IsChecked == true)
                caseDerivations.Add(new CaseDerivation { IdComplaint = idComplaint, Institution = chkDerivDefensory.Content.ToString(), Status = false });
            if (chkDerivOther.IsChecked == true)
                caseDerivations.Add(new CaseDerivation { IdComplaint = idComplaint, Institution = chkDerivOther.Content.ToString(), Status = false });
            return caseDerivations;
        }

        public void GetComplainantActorInfo(long idComplaint)
        {
            long ciPerson = long.Parse(tbCompCI.Text);
            Person complainant;
            if (PersonAndActorDataAccess.PersonAlreadyExists(ciPerson, tbCompName.Text, tbCompLastName.Text, tbCompMiddleName.Text))
            {
                var personComp = PersonAndActorDataAccess.GetPersonByCi(ciPerson);
                //Add all data that is not in direct action
                if (personComp != null)
                {
                    personComp.Gender = rbtnMaleComp.IsChecked == true ? "M" : "F";
                    personComp.Nationality = cboxCompCountry.SelectedItem.ToString();
                }
                complainant = PersonAndActorDataAccess.UpdatePerson(ciPerson, personComp);
            }
            else
            {
                var personComplainant = new Person();
                personComplainant.Id = tbCompCI.Text + DateTime.Now.Date.ToString(
                    CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern);
                personComplainant.CiPassport = long.Parse(tbCompCI.Text);
                personComplainant.Name = tbCompName.Text;
                personComplainant.PaternalName = tbCompLastName.Text;
                personComplainant.MaternalName = tbCompMiddleName.Text;
                personComplainant.BirthDate = CompBornDate.DisplayDate;
                personComplainant.Gender = rbtnMaleComp.IsChecked == true ? "M" : "F";
                personComplainant.Phone = tbCompPhone.Text;
                personComplainant.Address = tbCompAddress.Text;
                personComplainant.Zone = tbCompZone.Text;
                personComplainant.Nationality =
                    cboxCompCountry.SelectedItem.ToString();
                personComplainant.Ocupation = tbCompJob.Text;
                personComplainant.CivilStatus =
                    (cbCompCivilStatus.SelectedItem as ComboBoxItem).Content.ToString();
                personComplainant.RegisterDate = DateTime.Parse(DateTime.Now.Date.ToString(
     CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern));
                if(CurrentComplaint==null)
                    complainant = PersonAndActorDataAccess.InsertPerson(personComplainant);
                else
                {
                    complainant = PersonAndActorDataAccess.UpdatePerson(personComplainant.CiPassport, personComplainant);
                }
            }
            if (!PersonAndActorDataAccess.ActorAlreadyExists(complainant.Id, idComplaint,"Denunciante"))
            {
                PersonAndActorDataAccess.InsertActor(new Actor { IdPerson = complainant.Id, IdComplaint = idComplaint, Type = "Denunciante" });
            }
        }

        public void GetAggressorActorInfo(long idComplaint)
        {
            long ciPerson = long.Parse(tbAggressorCi.Text);
            Person aggressor;
            if (PersonAndActorDataAccess.PersonAlreadyExists(ciPerson, tbAggressorName.Text, tbAggressorLastName.Text, tbAggressorMiddleName.Text))
            {
                var personComp = PersonAndActorDataAccess.GetPersonByCi(ciPerson);
                //Add all data that is not in direct action
                if (personComp != null)
                {
                    personComp.Gender = rbtnMaleAggressor.IsChecked == true ? "M" : "F";
                    personComp.Nationality = cbAggressorCountry.SelectedItem.ToString();
                }
                aggressor = PersonAndActorDataAccess.UpdatePerson(ciPerson, personComp);
            }
            else
            {
                var personAggressor = new Person
                {
                    Id = tbAggressorCi.Text + DateTime.Now.Date.ToString(
                                  CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern),
                    CiPassport = long.Parse(tbAggressorCi.Text),
                    Name = tbAggressorName.Text,
                    PaternalName = tbAggressorLastName.Text,
                    MaternalName = tbAggressorMiddleName.Text,
                    BirthDate = AggressorBornDate.DisplayDate,
                    Gender = rbtnMaleAggressor.IsChecked == true ? "M" : "F",
                    Phone = tbAggressorPhone.Text,
                    CivilStatus =
                        (cbAggressorCivilStatus.SelectedItem as ComboBoxItem).Content.ToString(),
                    Nationality =
                    cbAggressorCountry.SelectedItem.ToString(),
                    BornCity = tbAggressorBornPlace.Text,
                    BornArea = rbtnAggressorRural.IsChecked==true?"Urbana":rbtnAggressorUrban.IsChecked==true?"Rural":null,
                    LevelOfEducation = (cbAggressorInstructionLevel.SelectedItem as ComboBoxItem).Content.ToString(),
                    ActivityStatus = rbtnAggressorCondActBusy.IsChecked == true ? rbtnAggressorCondActBusy.Content.ToString() : (rbtnAggressorCondActFree.IsChecked == true ? rbtnAggressorCondActFree.Content.ToString() : rbtnAggressorCondActInactive.IsChecked==true?rbtnAggressorCondActInactive.Content.ToString():null),
                    RegisterDate = DateTime.Parse(DateTime.Now.Date.ToString(
                                  CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern))
                };
                if(CurrentComplaint==null)
                    aggressor = PersonAndActorDataAccess.InsertPerson(personAggressor);
                else
                {
                    aggressor = PersonAndActorDataAccess.UpdatePerson(personAggressor.CiPassport, personAggressor);
                }
            }
            if (!PersonAndActorDataAccess.ActorAlreadyExists(aggressor.Id, idComplaint,"Agresor"))
            {
                PersonAndActorDataAccess.InsertActor(new Actor { IdPerson = aggressor.Id, IdComplaint = idComplaint, Type = "Agresor" });
            }
        }

        public void GetVictimActorInfo(long idComplaint)
        {
            long ciPerson = long.Parse(tbVictimCI.Text);
            Person victim;
            if (PersonAndActorDataAccess.PersonAlreadyExists(ciPerson,tbVictimName.Text, tbVictimLastName.Text,tbVictimMiddleName.Text))
            {
                var personComp = PersonAndActorDataAccess.GetPersonByCi(ciPerson);
                //Add all data that is not in direct action
                if (personComp != null)
                {
                    personComp.Gender = rbtnMaleVictim.IsChecked == true ? "M" : "F";
                    personComp.Nationality = cbVictimCountry.SelectedItem.ToString();
                }
                victim = PersonAndActorDataAccess.UpdatePerson(ciPerson, personComp);
            }
            else
            {
                var personComplainant = new Person
                {
                    Id = tbVictimCI.Text + DateTime.Now.Date.ToString(
                                  CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern),
                    CiPassport = long.Parse(tbVictimCI.Text),
                    Name = tbVictimName.Text,
                    PaternalName = tbVictimLastName.Text,
                    MaternalName = tbVictimMiddleName.Text,
                    BirthDate = VictimBornDate.DisplayDate,
                    Gender = rbtnMaleVictim.IsChecked == true ? "M" : "F",
                    Phone = tbVictimPhone.Text,
                    CivilStatus =
                        (cbVictimCivilStatus.SelectedItem as ComboBoxItem).Content.ToString(),
                    Nationality =
                    cbVictimCountry.SelectedItem.ToString(),
                    BornCity = tbVictimBornPlace.Text,
                    BornArea = rbtnVictimUrban.IsChecked == true ? "Urbana" :rbtnVictimRural.IsChecked==true?"Rural":null,
                    LevelOfEducation = (cbVictimInstructionLevel.SelectedItem as ComboBoxItem).Content.ToString(),
                    ActivityStatus = rbtnVictimCondActBusy.IsChecked == true ? rbtnVictimCondActBusy.Content.ToString() : (rbtnVictimCondActFree.IsChecked == true ? rbtnVictimCondActFree.Content.ToString() : rbtnVictimCondActInactive.IsChecked==true?rbtnVictimCondActInactive.Content.ToString():null),
                    RegisterDate = DateTime.Parse(DateTime.Now.Date.ToString(
                                  CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern))
                };
                victim = PersonAndActorDataAccess.InsertPerson(personComplainant);
            }
            if (!PersonAndActorDataAccess.ActorAlreadyExists(victim.Id, idComplaint,"Victima"))
            {
                PersonAndActorDataAccess.InsertActor(new Actor { IdPerson = victim.Id, IdComplaint = idComplaint, Type = "Victima" });
            }
        }

        private void ViolenceCauseChecked(object sender, RoutedEventArgs e)
        {
            lblViolenceCauseError.Content = "";
        }

        private void IncidentPlaceChecked(object sender, RoutedEventArgs e)
        {
            lblIncidentPlaceError.Content = "";
        }

        private void IncidentZoneChecked(object sender, RoutedEventArgs e)
        {
            lblIncidentZoneError.Content = "";
        }

        private void ViolenceFormChecked(object sender, RoutedEventArgs e)
        {
            lblViolenceFormError.Content = "";
        }

        private void CasesAtentionChecked(object sender, RoutedEventArgs e)
        {
            lblCasesAtentionError.Content = "";
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            if (CheckHasErrors())
                Xceed.Wpf.Toolkit.MessageBox.Show("No puede imprimir la denuncia hasta haber completado todos los campos obligatorios!","Información",MessageBoxButton.OK,MessageBoxImage.Information);
            else
            {
                PrintDialog pd = new PrintDialog();
                if ((bool)pd.ShowDialog().GetValueOrDefault())
                { 
                    this.tbAggressorImage.Visibility =Visibility.Collapsed;
                    this.btnPutAggressorImage.Visibility = Visibility.Collapsed;
                    this.SaveAndContinue.Visibility = Visibility.Collapsed;
                    this.btnPutVictimImage.Visibility = Visibility.Collapsed;
                    this.tbVictimImage.Visibility = Visibility.Collapsed;
                    pd.PrintVisual((UIElement) this, "Printing document");
                    this.SaveAndContinue.Visibility = Visibility.Visible;
                    this.tbAggressorImage.Visibility = Visibility.Visible;
                    this.btnPutAggressorImage.Visibility = Visibility.Visible;
                    this.btnPutVictimImage.Visibility = Visibility.Visible;
                    this.tbVictimImage.Visibility = Visibility.Visible;
                }
            }
        }

        private void BtnPutAggressorImage_OnClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg";
            DialogResult dgRes = openDialog.ShowDialog();
            if (dgRes == DialogResult.OK)
            {
                tbAggressorImage.Text = openDialog.FileName;
                AggressorPhoto.Source = new BitmapImage(new Uri(openDialog.FileName));
            }
        }

        private void BtnPutVictimImage_OnClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg";
            DialogResult dgRes = openDialog.ShowDialog();
            if (dgRes == DialogResult.OK)
            {
                tbVictimImage.Text = openDialog.FileName;
                VictimPhoto.Source = new BitmapImage(new Uri(openDialog.FileName));
            }
        }
    }

}
